//
//  ConsumeDetailViewController.m
//  Consume100
//
//  Created by eliot on 16/3/25.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "ConsumeDetailViewController.h"
#import "ShopHistoryTableViewCell.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"

#import "SecurityUtil.h"
#import "GTMBase64.h"


@interface ConsumeDetailViewController ()<UITableViewDataSource, UITableViewDelegate>


@property (weak, nonatomic) IBOutlet UIView *btnBGV;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btnBGVW;


@property (weak, nonatomic) IBOutlet UIButton *tobeSubmitBtn;


@property (weak, nonatomic) IBOutlet UIButton *shopHistoryBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 用于存储点击的哪个按钮*/
@property (nonatomic, assign) BOOL isHistory;


/** 待确认数据*/
@property (nonatomic, strong) NSMutableArray *firstArr;

/** 购买历史数据*/
@property (nonatomic, strong) NSMutableArray *secondArr;

@end



@implementation ConsumeDetailViewController

static int page = 1;

- (void)dealloc {
    page = 1;
}


-(NSMutableArray *)firstArr {
    if (!_firstArr) {
        _firstArr = [NSMutableArray array];
    }
    return _firstArr;
}
-(NSMutableArray *)secondArr {
    if (!_secondArr) {
        _secondArr = [NSMutableArray array];
    }
    return _secondArr;
}

+(ConsumeDetailViewController*)CreatConsumeDetailViewController{
    
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ConsumeDetailViewController *consume=[story instantiateViewControllerWithIdentifier:@"ConsumeDetailViewController"];
    return consume;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHistory = NO;
    
    self.btnBGV.layer.borderWidth = 1;
    self.btnBGV.layer.borderColor = [[UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1] CGColor];
    self.btnBGV.layer.cornerRadius = 4;
    self.btnBGV.layer.masksToBounds = YES;
    self.btnBGVW.constant = 160 / 320.0 *Width;
    
    /** 设置刷新*/
    
     MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
   // MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer = footer;
    
    /** 注册*/
    [self.tableView registerNib:[UINib nibWithNibName:@"ShopHistoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShopHistoryTableViewCell"];
    self.title = @"消费订单";
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithRed:232/255.0 green:233/255.0 blue:232/255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationController.navigationBar.translucent = NO;
    
    self.tobeSubmitBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    
    self.shopHistoryBtn.backgroundColor = [UIColor whiteColor];
    self.isHistory = NO;
    [self.shopHistoryBtn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
    
    
    UserModel *model = userModel;
    
    NSString *userid = [SecurityUtil encryptAESData:model.id];
    
    
    /** 消费订单  数据*/
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":@"1",@"consumerId":userid,@"confirmReceipt":@"0"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@lbsShopOrder.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            NSLog(@"%@", dddic);
            
            
            self.firstArr = [NSMutableArray arrayWithArray:dddic[@"datas"]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
}

- (void)loadMoreData {
    page += 1;
    UserModel *model = userModel;
    if (self.isHistory == NO) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 5;
        NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"confirmReceipt":@"0"};
        NSString *baseUrl = [NSString stringWithFormat:@"%@lbsShopOrder.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.mj_footer endRefreshing];
                [self.firstArr addObjectsFromArray:dddic[@"datas"]];
                [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView.mj_footer endRefreshing];
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
        
    }else {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 5;
        NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"confirmReceipt":@"1"};
        NSString *baseUrl = [NSString stringWithFormat:@"%@lbsShopOrder.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.mj_footer endRefreshing];
                [self.secondArr addObjectsFromArray:dddic[@"datas"]];
                [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView.mj_footer endRefreshing];
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isHistory == 0) {
        return self.firstArr.count;
    }else {
        return self.secondArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShopHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShopHistoryTableViewCell" forIndexPath:indexPath];
    cell.deleteBtn.backgroundColor = [UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (!self.isHistory) {
        cell.deleteBtn.hidden = YES;
        cell.submitBtn.hidden = NO;
        cell.buyAgainBtn.hidden =  YES;
        NSArray *arr = self.firstArr[indexPath.section];
        NSDictionary *dic1 = arr.firstObject;
        NSDictionary *dic2 = arr[1];
        
        
        
        cell.titleLb.text = [NSString stringWithFormat:@"%@(%@)", dic2[@"name"], dic1[@"address"]];
        [cell.icon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@", dic2[@"img"]]]];
        cell.priceLb.text = [NSString stringWithFormat:@"￥%@", arr[2][@"price"]];
        cell.countLb.text = [NSString stringWithFormat:@"%d", [dic2[@"sum"] intValue]];
        
        
    }else {
        
        cell.deleteBtn.hidden = NO;
        cell.submitBtn.hidden = YES;
        cell.buyAgainBtn.hidden =  NO;
        
        NSArray *arr = self.secondArr[indexPath.section];
        NSDictionary *dic1 = arr.firstObject;
        NSDictionary *dic2 = arr[1];

  
        cell.titleLb.text = [NSString stringWithFormat:@"%@(%@)", dic2[@"name"], dic1[@"address"]];
        [cell.icon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.188:8080%@", dic2[@"img"]]]];
        cell.priceLb.text = [NSString stringWithFormat:@"￥%@", arr[2][@"price"]];
        cell.countLb.text = [NSString stringWithFormat:@"%d", [dic2[@"sum"] intValue]];
 
    }
    cell.submitBtn.tag = indexPath.section;
    cell.deleteBtn.tag = indexPath.section;
    [cell.submitBtn addTarget:self action:@selector(clicksubmitBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cell.deleteBtn addTarget:self action:@selector(clickDeleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 12;
}

/** 点击确认收货*/
- (void)clicksubmitBtn:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否确认收货" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        NSArray *arr = self.secondArr[sender.tag];
        NSDictionary *dic1 = arr.firstObject;
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 5;
        NSDictionary *dic = @{@"integralShopOrderId":dic1[@"lbsBusinessId"]};
        NSString *baseUrl = [NSString stringWithFormat:@"%@confirmReceipt.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.firstArr removeObject:arr];
            
                 [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
        
        
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
    
}
/** 点击删除订单*/
- (void)clickDeleteBtn:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否删除订单" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UserModel *model = userModel;
        NSArray *arr = self.secondArr[sender.tag];
        NSDictionary *dic1 = arr.firstObject;
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 5;
        NSDictionary *dic = @{@"lbsOrderId":dic1[@"lbsBusinessId"], @"consumerId":[SecurityUtil encryptAESData:model.id]};
        NSString *baseUrl = [NSString stringWithFormat:@"%@delLbsOrder.jhtml", MyBaseURL];
        [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.secondArr removeObject:arr];
                [self.tableView reloadData];
                
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:@"链接超时,请检查网络"];
            });
        }];
        
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
    
}

/** 点击待确认*/
- (IBAction)clickToBeSubmitBtn:(id)sender {
    
    UserModel *model = userModel;
    page = 1;
    
    self.isHistory = NO;
    self.tobeSubmitBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
        
    self.shopHistoryBtn.backgroundColor = [UIColor whiteColor];
    [self.shopHistoryBtn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
    [self.tobeSubmitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"confirmReceipt":@"0"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@lbsShopOrder.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.firstArr = [NSMutableArray  arrayWithArray:dddic[@"datas"]];
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
    
    
  
    
}
/** 点击购历史*/
- (IBAction)clickHistoryBtn:(id)sender {
    self.isHistory = YES;
    UserModel *model = userModel;
    page = 1;
    self.shopHistoryBtn.backgroundColor = [UIColor colorWithRed:254/255.0 green:154/255.0 blue:37/255.0 alpha:1];
    self.tobeSubmitBtn.backgroundColor = [UIColor whiteColor];
    [self.tableView reloadData];
    [self.tobeSubmitBtn setTitleColor:[UIColor colorWithRed:136/255.0 green:136/255.0 blue:136/255.0 alpha:1] forState:UIControlStateNormal];
    [self.shopHistoryBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 5;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d", page],@"consumerId":[SecurityUtil encryptAESData:model.id],@"confirmReceipt":@"1"};
    NSString *baseUrl = [NSString stringWithFormat:@"%@lbsShopOrder.jhtml", MyBaseURL];
    [manager POST:baseUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dddic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.secondArr = [NSMutableArray  arrayWithArray:dddic[@"datas"]];
  
            [self.tableView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"链接超时,请检查网络"];
        });
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
